<template>
  <el-page-header @back="handleBack" class="page-header">
    <template #icon>
      <el-icon>
        <ArrowLeft />
      </el-icon>
    </template>
    <template #content>
      <span class="text-large font-600 mr-3"> 团队管理 </span>
    </template>
  </el-page-header>

  <el-tabs
      v-model="activeName"
      class="demo-tabs mt-4"
      @tab-click="handleTabClick"
  >
    <el-tab-pane label="我管理的团队" name="managed">
      <el-form :model="form" label-width="auto" class="search-form">
        <el-form-item label="所属机构">
          <el-select v-model="form.region" placeholder="请选择机构" class="form-select">
            <el-option  v-for="org in region"
                        :key="org.id"
                        :label="org.orgName"
                        :value="org.id" />
          </el-select>
        </el-form-item>
        <el-form-item >
          <el-input v-model="form.name" placeholder="请输入关键字" class="form-input"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchTeam" class="search-btn">搜索</el-button>
          <el-button type="primary" @click="zhikong" class="search-btn">置空</el-button>
          <el-button type="primary" @click="addTeam" class="add-btn">新增医生团队</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="managedTeamForm" style="width: 100%" v-loading="loading" class="team-table">
        <el-table-column fixed prop="id" label="编号" width="100" />
        <el-table-column prop="teamName" label="团队名称" width="200" />
        <el-table-column prop="leaderName" label="团队队长" width="100" />
        <el-table-column prop="label" label="团队标签" width="200" >
          <template #default="scope">
            <div class="team-label-container">
              <span v-for="(tag,index) in scope.row.label.split(',')" :key="index" class="team-tag">
                {{tag}}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="orgName" label="所属机构" width="250" />
        <el-table-column prop="count" label="签约人数" width="120" />
        <el-table-column prop="status" label="状态" width="120" >
          <template #default="scope">
            <el-switch
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="2"
                @change="statusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="120">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleViewDetail(scope.row.id)">
              查看详情
            </el-button>
            <el-button link type="primary" size="small" @click="outTeam(scope.row.id)">
              解散团队
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>
    <el-tab-pane label="我加入的团队" name="joined">
      <el-form :model="form" label-width="auto" class="search-form">
        <el-form-item label="所属机构">
          <el-select v-model="form.region" placeholder="请选择机构" class="form-select">
            <el-option v-for="org in region"
                       :key="org.id"
                       :label="org.orgName"
                       :value="org.id" />
          </el-select>
        </el-form-item>
        <el-form-item >
          <el-input v-model="form.name" placeholder="请输入关键字" class="form-input"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchTeam" class="search-btn">搜索</el-button>
          <el-button type="primary" @click="zhikong" class="search-btn">置空</el-button>
          <el-button type="primary" @click="joinTeam" class="add-btn">加入医生团队</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="joinedTeamForm" style="width: 100%" v-loading="loading" class="team-table">
        <el-table-column fixed prop="id" label="编号" width="100" />
        <el-table-column prop="teamName" label="团队名称" width="200" />
        <el-table-column prop="leaderName" label="团队队长" width="100" />
        <el-table-column prop="label" label="团队标签" width="200" >
          <template #default="scope">
            <div class="team-label-container">
              <span v-for="(tag,index) in scope.row.label.split(',')" :key="index" class="team-tag">
                {{tag}}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="orgName" label="所属机构" width="250" />
        <el-table-column prop="count" label="签约人数" width="120" />
        <el-table-column prop="status" label="状态" width="120" >
          <template #default="scope">
            <span :class="scope.row.status === 1 ? 'status-active' : 'status-inactive'">
      {{ scope.row.status === 1 ? '启用中' : '禁用中' }}
    </span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="120">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleViewDetail(scope.row.id)">
              查看详情
            </el-button>
            <el-button link type="primary" size="small" @click="exitTeam(scope.row.id)">
              退出团队
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>
  </el-tabs>
</template>
<script>
import { ArrowLeft } from "@element-plus/icons-vue";
import { ElIcon } from "element-plus";
import {deleteSysTeam, findSysTeam, updateSysDoctorTeam, updateSysTeam} from "../api/SysTeam.js";
import {findAllSysOrganization} from "../api/SysOrganization.js";
import {selectSysTeam} from "../api/SysTeamOrganization.js";
export default {
  name: "SysTeam",
  components: {
    ArrowLeft,
    ElIcon
  },
  data() {
    return {
      activeName: "managed",
      managedTeamForm: [],
      joinedTeamForm: [],
      loading: false,
      doctorId: this.getDoctorIdFromLocalStorage() ||1,
      form:{},
      region: [],
    };
  },
  methods: {
    async statusChange(row){
      const params = {
        id: row.id,
        status: row.status
      };
      let {data:data}=await updateSysTeam(params)
    },
    async zhikong(){
      this.form = {
        region: "",
        name: "" ,
      };
      await this.searchTeam();
    },
    async loadOrganization() {
      let { data: data } = await findAllSysOrganization();
      console.log("查询所有机构数据：", data.data)
      this.region = data.data;
    },
    async joinTeam(){
      console.log("添加团队",this.doctorId)
      this.$router.push({
        path: "/JoinTeam",
        query: { doctorId: this.doctorId }
      });
    },
    async addTeam(){
      console.log("添加团队",this.doctorId)
      this.$router.push({
        path: "/AddTeam",
        query: { doctorId: this.doctorId }
      });
    },
    async searchTeam(){
      const searchParams = {
        doctorId: this.doctorId,
        role: this.activeName === "managed" ? 1 : 2,
        orgId: this.form.region,
        teamName: this.form.name?.trim() || ""
      };
      console.log("搜索参数：", searchParams);
        let { data: res } = await selectSysTeam(searchParams);
        if (res.code === 200) {
          if (this.activeName === "managed") {
            this.managedTeamForm = res.data || [];
          } else {
            this.joinedTeamForm = res.data || [];
          }
        }
    },
    async exitTeam(id) {
      console.log("退出团队，ID：", id);
      let {data:data}=await updateSysDoctorTeam(this.doctorId,id)
      if(data.code==200){
        this.$message.success("退出团队成功")
        this.loadData()
      }else{
        this.$message.error("退出团队失败")
      }
    },
    async outTeam(id) {
      console.log("解散团队，ID：", id);
      let {data:data}=await deleteSysTeam(id)
      if(data.code==200){
        this.$message.success("解散团队成功")
        this.loadData()
      }else{
        this.$message.error("解散团队失败")
      }
    },
    handleBack() {
      this.$router.go(-1);
    },
    handleTabClick(tab) {
      console.log("点击的标签原始数据：", tab);
      const tabName = tab.props.name;
      console.log("提取的标签name：", tabName);
      this.activeName = tabName;
      console.log("赋值后activeName：", this.activeName);
      this.loadData();
    },

    async loadData() {
      this.loading = true;
      try {
        let role;
        if (this.activeName === "managed") {
          role = 1;
        } else if (this.activeName === "joined") {
          role = 2;
        } else {
          role = 1;
          console.warn("activeName异常，强制使用role=1");
        }
        console.log("当前activeName：", this.activeName);
        console.log("最终使用的role：", role);
        const response = await findSysTeam(role, this.doctorId);
        const teamList = response.data?.data || [];
        console.log("接口返回数据：", teamList);
        if (this.activeName === "managed") {
          this.managedTeamForm = teamList;
        } else {
          this.joinedTeamForm = teamList;
        }
      } catch (error) {
        console.error("查询失败：", error);
        this.$message.error("获取团队数据失败，请重试");
      } finally {
        this.loading = false;
      }
    },

    async handleViewDetail(id) {
      console.log("查看团队详情，ID：", id);
      this.$router.push(`/sysTeamDetail/${id}`)
    },

    getDoctorIdFromLocalStorage() {
      const userStr = localStorage.getItem("doctorUser");
      if (!userStr) return null;
      const user = JSON.parse(userStr);
      return user.id;
    },
  },
  mounted() {
    console.log("页面初始化activeName：", this.activeName);
    this.loadData();
    this.loadOrganization();
  },
};
</script>
<style scoped>
.mt-4 {
  margin-top: 16px;
}

/* 页面头部样式 */
.page-header {
  margin: 16px 0;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

/* 搜索表单样式 */
.search-form {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background-color: #f9fafb;
  border-radius: 6px;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.form-select {
  width: 200px;
}

.form-input {
  width: 240px;
}

.search-btn {
  margin-right: 8px;
}

.add-btn {
  background-color: #36d399;
  border-color: #36d399;
}

.add-btn:hover {
  background-color: #2cb67d;
  border-color: #2cb67d;
}

/* 表格样式 */
.team-table {
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

/* 表格行样式 */
::v-deep .team-table .el-table__row {
  transition: background-color 0.2s;
}

::v-deep .team-table .el-table__row:hover > td {
  background-color: #f0f9ff !important;
}

/* 表格头部样式 */
::v-deep .team-table .el-table__header th {
  background-color: #f8fafc;
  font-weight: 600;
  color: #334155;
}

/* 操作按钮样式 */
::v-deep .el-button--text {
  color: #3b82f6;
  padding: 4px 8px;
}

::v-deep .el-button--text:hover {
  color: #2563eb;
  background-color: rgba(59, 130, 246, 0.1);
}

/* 标签页样式 */
::v-deep .demo-tabs .el-tabs__nav {
  padding: 0 16px;
}

::v-deep .demo-tabs .el-tabs__active-bar {
  background-color: #3b82f6;
}

::v-deep .demo-tabs .el-tabs__item.is-active {
  color: #3b82f6;
  font-weight: 500;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: flex-start;
  }

  .form-select, .form-input {
    width: 100%;
  }
}
.team-label-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.team-tag {
  background-color: #e6f7ff;
  color: #1890ff;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}
</style>
